package kau.dao;

import org.apache.ibatis.session.SqlSession;

import kau.common.DBUtil;
import kau.exception.DuplicationException;
import kau.exception.RecordNotFoundException;
import kau.vo.Curriculum;
import kau.vo.Course;

public class CurriculumDAOImpl implements CurriculumDAOIF {

	DBUtil db = null;
	private static CurriculumDAOImpl instance;
	
	private CurriculumDAOImpl() {
		db = DBUtil.getInstance();
	}
	public static CurriculumDAOImpl getInstance(){
		if( instance == null) instance = new CurriculumDAOImpl();
		return instance;
	}
	
	private boolean isExist(int courseId) {
		SqlSession session = db.getSession();
		boolean flag = false;
		String result = null;
		try{
			result = session.selectOne("dbConfig.CurriculumMapper.isExist",courseId);
		}finally{
			session.close();
		}
		if(result!= null) flag= true;
		
		return flag;
	}
	@Override
	public void insert(Curriculum curriculum) throws DuplicationException {
		if(isExist(curriculum.getCourseId())) throw new DuplicationException(curriculum.getCourseId());
		SqlSession session = db.getSession();
		try{
			session.insert("dbConfig.CurriculumMapper.insert", curriculum);
			session.commit();
		}finally{
			session.close();
		}
	}

	@Override
	public void update(Curriculum curriculum) throws RecordNotFoundException {
		if(!isExist(curriculum.getCourseId())) throw new RecordNotFoundException(curriculum.getCourseId());
		SqlSession session = db.getSession();
		try{
			session.update("dbConfig.CurriculumMapper.update", curriculum);
			session.commit();
		}finally{
			session.close();
		}

	}

	@Override
	public void delete(int courseId) throws RecordNotFoundException {
		if(!isExist(courseId)) throw new RecordNotFoundException(courseId);
		SqlSession session = db.getSession();
		try{
			session.delete("dbConfig.CurriculumMapper.delete", courseId);
			session.commit();
		}finally{
			session.close();
		}

	}

	@Override
	public Curriculum getCurriculum(int courseId)
			throws RecordNotFoundException {
		if(!isExist(courseId)) throw new RecordNotFoundException(courseId);
		SqlSession session = db.getSession();
		Curriculum curriculum=null;
		try{
			curriculum = session.selectOne("dbConfig.CurriculumMapper.getCurriculum", courseId);
		}finally{
			session.close();
		}
		
		return curriculum;
	}
	
	

}
